package com.infore.airsupervise.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.PopupMenu;
import android.widget.TextView;

import com.beardedhen.androidbootstrap.font.FontAwesome;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.infore.airsupervise.R;
import com.infore.airsupervise.app.Constants;
import com.infore.airsupervise.bean.PolluterE;
import com.infore.airsupervise.biz.PolluterBiz;
import com.infore.airsupervise.biz.impl.PolluterBizImpl;
import com.infore.airsupervise.http.OnServerResponseListener;
import com.infore.airsupervise.ui.widget.SwipeRecyclerView;
import com.infore.airsupervise.utils.JumpUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 污染源查询
 *
 * @作者: dingxinlin
 * @创建时间: 2017/4/12 15:40
 */
public class PolluterSearchActivity
        extends BaseTitleBarActivity
        implements SwipeRecyclerView.OnActionListener {

    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.refreshRecyclerView)
    SwipeRecyclerView swipeRecyclerView;
    @BindView(R.id.tv_search)
    TextView tvSearch;

    private PolluterBiz polluterBiz;

    private List<PolluterE> datas = new ArrayList<>();
    private BaseQuickAdapter<PolluterE, BaseViewHolder> quickAdapter;

    private int searchType = 1;

    private int from_state ; //activity跳转标识

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_polluter_search);
        ButterKnife.bind(this);
        Intent it = getIntent();
        if(null!= it){
            from_state= it.getIntExtra(Constants.INTENT_INT_KEY,0);
        }
        polluterBiz = new PolluterBizImpl();

        initView();
    }

    /**
     * 初始化控件
     */
    private void initView() {
        title.setText("污染源查询");
        rightMenu.setFontAwesomeIcon(FontAwesome.FA_FILTER);
        tvSearch.setText("搜索");
        // 键盘搜索按钮监听
        etSearch.setHint("搜索企业名称/污染源名称");
        etSearch.setImeActionLabel("搜索",EditorInfo.IME_ACTION_SEARCH);
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    swipeRecyclerView.getSwipeLayout().setRefreshing(true);
                    swipeRecyclerView.onRefresh();
                    return true;
                }
                return false;
            }
        });

        // 适配器
        quickAdapter = new BaseQuickAdapter<PolluterE, BaseViewHolder>(R.layout.item_polluter_list, datas) {
            @Override
            protected void convert(BaseViewHolder helper, final PolluterE item) {
                helper.setText(R.id.polluter_name, item.getName());
                helper.setText(R.id.polluter_mn, "MN编号：" + item.getMn());
                helper.setText(R.id.polluter_address, "地址：" + item.getAddress());
                helper.setText(R.id.polluter_grid, "所属网格：" + item.getGrid());
            }
        };

        // 设置recyclerView
        swipeRecyclerView.setAdapter(quickAdapter);
        swipeRecyclerView.setActionListener(this);

        // 首次自动刷新
        swipeRecyclerView.getSwipeLayout().setRefreshing(true);
        swipeRecyclerView.onRefresh();
    }

    @Override
    public void onRefresh() {
        searchPolluterDatas(true);
    }

    @Override
    public void onLoadMore() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                swipeRecyclerView.getAdapter().loadMoreEnd();
                swipeRecyclerView.getSwipeLayout().setEnabled(true);
            }
        }, 1000);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        PolluterE item = datas.get(position);
        switch (from_state){
            case 0 :
                // 跳转到污染源详情
                JumpUtil.jumpFromTo(
                        ctx, PolluterDetailActivity.class, Constants.INTENT_STR_KEY, item.getMn());
                break;
            case 1 :
                //回到任务创建界面
                //回到现场监察记录创建界面
                Intent it= new Intent();
                it.putExtra(Constants.INTENT_OBJ_KEY,item);
                setResult(RESULT_OK,it);
                finish();
                break;
        }
    }

    /**
     * 搜索污染源
     */
    private void searchPolluterDatas(final boolean isRefresh) {
        polluterBiz.searchPolluter(searchType, etSearch.getText().toString(),
                new OnServerResponseListener<List<PolluterE>>() {
                    @Override
                    public void onSucceed(List<PolluterE> result, String desc) {
                        swipeRecyclerView.commonSuccessHandle(isRefresh, result.size());

                        datas.clear();
                        datas.addAll(result);
                        swipeRecyclerView.getAdapter().notifyDataSetChanged();
                    }

                    @Override
                    public void onFailed(int errorCode, String title, String desc) {
                        swipeRecyclerView.commonFailedHandle(isRefresh, errorCode, title, desc);
                    }
                });
    }

    @Override
    protected void onRightMenuClick(View view) {
        super.onRightMenuClick(view);

        PopupMenu popupMenu = new PopupMenu(ctx, rightMenu);
        popupMenu.getMenuInflater().inflate(R.menu.source_query_type, popupMenu.getMenu());
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                switch (menuItem.getItemId()) {
                    case R.id.menu_company_name:
                        searchType = 1;
                        break;
                    case R.id.menu_mn:
                        searchType = 2;
                        break;
                    case R.id.menu_address:
                        searchType = 3;
                        break;
                    case R.id.menu_grid_name:
                        searchType = 4;
                        break;
                }
                etSearch.setHint("搜索" + menuItem.getTitle());
                return true;
            }
        });
        popupMenu.show();
    }

    @OnClick(R.id.iv_searchClean)
    void onClearBtnClick() {
        etSearch.setText("");
    }

    @OnClick(R.id.tv_search)
    void onSearchBtnClick() {
        swipeRecyclerView.getSwipeLayout().setRefreshing(true);
        swipeRecyclerView.onRefresh();
    }
}
